package com.itg.vms.dao.impl;

import com.itg.vms.dao.LogDao;
import com.itg.vms.entity.vo.Log;
import com.itg.vms.util.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author zjzaki
 * @create 2023年03月11日 09:46:00
 */
public class LogDaoImpl implements LogDao {

    QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());

    /**
     * 插入日志
     *
     * @param userId 用户id
     * @param msg    信息
     * @param logIp 登录的ip
     * @return 影响的行数
     */
    @Override
    public int insertLog(Long userId, String msg,String logIp) {
        String sql = "insert into vms.sys_log values (?,?,?,sysdate())";
        int update = 0;
        try {
            update = queryRunner.update(sql,userId,msg,logIp);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }

    /**
     * 分页查询用户日志
     *
     * @param currentPage 当前页
     * @param pageSize    页面大小
     * @return 日志列表
     */
    @Override
    public List<Log> selectAllLog(Integer currentPage, Integer pageSize) {
        String sql = "SELECT a.user_id as userId, msg, login_ip as logIp, " +
                "logTime, user_name as userName, nick_name as nickName, user_type as userType, " +
                "email, phonenumber as phoneNumber " +
                "FROM vms.sys_log as a " +
                "LEFT JOIN vms.sys_user as b " +
                "ON a.user_id = b.user_id " +
                "ORDER BY logTime desc " +
                "LIMIT ?,?";
        List<Log> query = null;
        try {
            query = queryRunner.query(sql, new BeanListHandler<>(Log.class),currentPage,pageSize);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    /**
     * 得到所有表的数据条数
     *
     * @return 总条数
     */
    @Override
    public Long getAllLogSize() {
        String sql = "select COUNT(user_id) as sum from vms.sys_log";
        Long sum = 0L;
        try {
            sum = (Long) queryRunner.query(sql, new ScalarHandler("sum"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return sum;
    }
}
